<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公寓名称" prop="apartmentName">
        <el-input
          v-model="queryParams.apartmentName"
          placeholder="请输入公寓名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="业主" prop="ownerId">
        <el-select
          v-model="queryParams.ownerId"
          filterable
          remote
          reserve-keyword
          placeholder="请输入业主名称或身份证号"
          :remote-method="remoteSearchOwners"
          :loading="ownerLoading"
          clearable
        >
          <el-option
            v-for="item in ownerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="门牌号" prop="doorplate">
        <el-input
          v-model="queryParams.doorplate"
          placeholder="请输入门牌号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="租金(元/月)" prop="rent">
        <el-input
          v-model="queryParams.rent"
          placeholder="请输入租金"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.house_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['house:house:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['house:house:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['house:house:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['house:house:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="houseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="houseId" />
      <el-table-column label="公寓名称" align="center" prop="apartmentName" />
      <el-table-column label="业主" align="center" prop="ownerName" />
      <el-table-column label="门牌号" align="center" prop="doorplate" />
      <el-table-column label="图片" align="center" prop="pictureAddress" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.pictureAddress" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="租金(元/月)" align="center" prop="rent" />
      <el-table-column label="租客评价" align="center" prop="remark" />
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.house_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['house:house:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['house:house:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handleProperties(scope.row)"
            v-hasPermi="['house:properties:edit']"
          >属性</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改房屋管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="公寓名称" prop="apartmentId">
          <el-select v-model="form.apartmentId" placeholder="请选择公寓">
            <el-option
              v-for="item in apartmentOptions"
              :key="item.apartmentId"
              :label="item.apartmentName"
              :value="item.apartmentId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="业主" prop="ownerId">
          <el-select
            v-model="form.ownerId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入业主名称或身份证号"
            :remote-method="remoteSearchOwners"
            :loading="ownerLoading"
          >
            <el-option
              v-for="item in ownerOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="门牌号" prop="doorplate">
          <el-input v-model="form.doorplate" placeholder="请输入门牌号" />
        </el-form-item>
        <el-form-item label="图片" prop="pictureAddress">
          <image-upload v-model="form.pictureAddress"/>
        </el-form-item>
        <el-form-item label="租金(元/月)" prop="rent">
          <el-input v-model="form.rent" placeholder="请输入租金" />
        </el-form-item>
        <el-form-item label="租客评价" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio
              v-for="dict in dict.type.house_state"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改房屋属性对话框 -->
    <el-dialog :title="title" :visible.sync="openProperties" width="500px" append-to-body>
      <el-form ref="propertiesForm" :model="propertiesForm" :rules="propertiesRules" label-width="80px">
        <el-form-item label="占地面积" prop="floorSpace">
          <el-input v-model="propertiesForm.floorSpace" placeholder="请输入占地面积" />
        </el-form-item>
        <el-form-item label="房屋类型" prop="typeHouse">
          <el-input v-model="propertiesForm.typeHouse" placeholder="请输入房屋类型" />
        </el-form-item>
        <el-form-item label="朝向" prop="towards">
          <el-select v-model="propertiesForm.towards" placeholder="请选择朝向">
            <el-option
              v-for="dict in dict.type.house_towards"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设施" prop="facility">
          <el-input v-model="propertiesForm.facility" placeholder="请输入设施" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPropertiesForm">确 定</el-button>
        <el-button @click="cancelProperties">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHouse, getHouse, delHouse, addHouse, updateHouse, searchOwners } from "@/api/house/house";
import { listApartment } from "@/api/house/apartment";
import { getProperties, addProperties, updateProperties } from "@/api/house/properties";

export default {
  name: "House",
  dicts: ['house_state', 'house_towards'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 房屋管理表格数据
      houseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        apartmentName: null,
        ownerId: null,
        doorplate: null,
        rent: null,
        state: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        apartmentId: [
          { required: true, message: "公寓id不能为空", trigger: "blur" }
        ],
        ownerId: [
          { required: true, message: "业主id不能为空", trigger: "blur" }
        ],
        doorplate: [
          { required: true, message: "门牌号不能为空", trigger: "blur" }
        ],
        rent: [
          { required: true, message: "租金不能为空", trigger: "blur" }
        ],
        state: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      },
      apartmentOptions: [],
      ownerOptions: [],
      ownerLoading: false,
      // 属性表单参数
      propertiesForm: {
        houseId: null,
        floorSpace: '未知',
        typeHouse: '未知',
        towards: '未知',
        facility: '无'
      },
      // 属性表单校验
      propertiesRules: {
        floorSpace: [
          { required: true, message: "占地面积不能为空", trigger: "blur" }
        ],
        typeHouse: [
          { required: true, message: "房屋类型不能为空", trigger: "blur" }
        ],
        towards: [
          { required: true, message: "朝向不能为空", trigger: "change" }
        ],
      },
      // 属性对话框
      openProperties: false,
    };
  },
  created() {
    this.getList();
    this.getApartmentOptions();
    // 不需要在这里调用 this.getOwners()，因为我们现在使用远程搜索
  },
  methods: {
    /** 查询房屋管理列表 */
    getList() {
      this.loading = true;
      listHouse(this.queryParams).then(response => {
        this.houseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取公寓选项 */
    getApartmentOptions() {
      listApartment().then(response => {
        this.apartmentOptions = response.rows;
      });
    },
    /** 远程搜索业主 */
    remoteSearchOwners(query) {
      if (query !== '') {
        this.ownerLoading = true;
        searchOwners(query).then(response => {
          this.ownerOptions = response.data;
          this.ownerLoading = false;
        }).catch(() => {
          this.ownerLoading = false;
        });
      } else {
        this.ownerOptions = [];
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        houseId: null,
        apartmentId: null,
        ownerId: null,
        doorplate: null,
        pictureAddress: null,
        rent: null,
        remark: null,
        state: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.houseId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加房屋管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const houseId = row.houseId || this.ids
      getHouse(houseId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改房屋管理";
        this.$nextTick(() => {
          this.remoteSearchOwners(this.form.ownerId); // 确保在打开对话框后加载业主列表
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.houseId != null) {
            updateHouse(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHouse(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const houseIds = row.houseId || this.ids;
      this.$modal.confirm('是否确认除房屋管理编号为"' + houseIds + '"的数据项？').then(function() {
        return delHouse(houseIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('house/house/export', {
        ...this.queryParams
      }, `house_${new Date().getTime()}.xlsx`)
    },
    /** 处理属性按钮操作 */
    handleProperties(row) {
      this.reset();
      const houseId = row.houseId;
      getProperties(houseId).then(response => {
        this.propertiesForm = response.data || { houseId: houseId };
        this.openProperties = true;
        this.title = "编辑房屋属性";
      });
    },

    /** 取消按钮（属性） */
    cancelProperties() {
      this.openProperties = false;
      this.reset();
    },

    /** 提交按钮（属性） */
    submitPropertiesForm() {
      this.$refs["propertiesForm"].validate(valid => {
        if (valid) {
          if (this.propertiesForm.houseId != null) {
            updateProperties(this.propertiesForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openProperties = false;
              this.getList();
            });
          } else {
            addProperties(this.propertiesForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openProperties = false;
              this.getList();
            });
          }
        }
      });
    },
  }
};
</script>
